package com.zhentao.dataintegrity.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhentao.dataintegrity.domain.dto.ExecutionRecordDTO;
import com.zhentao.dataintegrity.domain.dto.SubtaskDetailDTO;
import com.zhentao.dataintegrity.service.IntegrityExecutionService;
import com.zhentao.subscription.common.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/dataintegrity/executions")
@CrossOrigin(origins = "*")
public class IntegrityExecutionController {

    private static final Logger log = LoggerFactory.getLogger(IntegrityExecutionController.class);

    @Autowired
    private IntegrityExecutionService executionService;

    /**
     * 分页查询执行记录
     */
    @GetMapping
    public R<IPage<ExecutionRecordDTO>> getExecutionPage(
            @RequestParam(defaultValue = "1") int pageNo,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) Long taskId,
            @RequestParam(required = false) String executionStatus,
            @RequestParam(required = false) String triggerType) {
        try {
            IPage<ExecutionRecordDTO> page = executionService.getExecutionPage(pageNo, pageSize, taskId, executionStatus, triggerType);
            return R.ok(page);
        } catch (Exception e) {
            log.error("查询执行记录失败", e);
            return R.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取执行记录详情
     */
    @GetMapping("/{executionId}")
    public R<ExecutionRecordDTO> getExecutionDetail(@PathVariable String executionId) {
        try {
            ExecutionRecordDTO execution = executionService.getExecutionDetail(executionId);
            if (execution == null) {
                return R.error("执行记录不存在");
            }
            return R.ok(execution);
        } catch (Exception e) {
            log.error("获取执行记录详情失败: executionId={}", executionId, e);
            return R.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询子任务详情
     */
    @GetMapping("/{executionId}/subtasks")
    public R<IPage<SubtaskDetailDTO>> getSubtaskPage(
            @PathVariable String executionId,
            @RequestParam(defaultValue = "1") int pageNo,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String dataTypeCode,
            @RequestParam(required = false) String executionStatus) {
        try {
            IPage<SubtaskDetailDTO> page = executionService.getSubtaskPage(pageNo, pageSize, executionId, dataTypeCode, executionStatus);
            return R.ok(page);
        } catch (Exception e) {
            log.error("查询子任务详情失败: executionId={}", executionId, e);
            return R.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 根据任务ID查询执行记录
     */
    @GetMapping("/by-task/{taskId}")
    public R<List<ExecutionRecordDTO>> getExecutionsByTaskId(@PathVariable Long taskId) {
        try {
            List<ExecutionRecordDTO> executions = executionService.getExecutionsByTaskId(taskId);
            return R.ok(executions);
        } catch (Exception e) {
            log.error("查询任务执行记录失败: taskId={}", taskId, e);
            return R.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 取消执行
     */
    @PostMapping("/{executionId}/cancel")
    public R<Boolean> cancelExecution(@PathVariable String executionId) {
        try {
            boolean success = executionService.cancelExecution(executionId);
            return success ? R.ok(true) : R.error("取消失败");
        } catch (Exception e) {
            log.error("取消执行失败: executionId={}", executionId, e);
            return R.error("取消失败: " + e.getMessage());
        }
    }

    /**
     * 获取运行中的执行记录
     */
    @GetMapping("/running")
    public R<List<ExecutionRecordDTO>> getRunningExecutions() {
        try {
            List<ExecutionRecordDTO> executions = executionService.getRunningExecutions();
            return R.ok(executions);
        } catch (Exception e) {
            log.error("获取运行中执行记录失败", e);
            return R.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 获取最近的执行记录
     */
    @GetMapping("/recent")
    public R<List<ExecutionRecordDTO>> getRecentExecutions(@RequestParam(defaultValue = "10") int limit) {
        try {
            List<ExecutionRecordDTO> executions = executionService.getRecentExecutions(limit);
            return R.ok(executions);
        } catch (Exception e) {
            log.error("获取最近执行记录失败", e);
            return R.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 清理历史记录
     */
    @PostMapping("/clean-history")
    public R<Boolean> cleanHistory(@RequestParam(defaultValue = "30") int keepDays) {
        try {
            boolean success = executionService.cleanHistory(keepDays);
            return success ? R.ok(true) : R.error("清理失败");
        } catch (Exception e) {
            log.error("清理历史记录失败", e);
            return R.error("清理失败: " + e.getMessage());
        }
    }

    /**
     * 导出任务列表
     */
    @GetMapping("/export/tasks")
    public ResponseEntity<byte[]> exportTaskList(
            @RequestParam(required = false) String taskTitle,
            @RequestParam(required = false) String taskStatus,
            @RequestParam(required = false) String triggerType) {
        try {
            byte[] data = executionService.exportTaskList(taskTitle, taskStatus, triggerType);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "integrity_tasks.xlsx");
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(data);
        } catch (Exception e) {
            log.error("导出任务列表失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 导出子任务详情
     */
    @GetMapping("/export/subtasks/{executionId}")
    public ResponseEntity<byte[]> exportSubtaskDetails(
            @PathVariable String executionId,
            @RequestParam(required = false) String dataTypeCode,
            @RequestParam(required = false) String executionStatus) {
        try {
            byte[] data = executionService.exportSubtaskDetails(executionId, dataTypeCode, executionStatus);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "subtask_details_" + executionId + ".xlsx");
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(data);
        } catch (Exception e) {
            log.error("导出子任务详情失败: executionId={}", executionId, e);
            return ResponseEntity.internalServerError().build();
        }
    }
}
